<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件合约交易平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header-left .logo {
            font-size: 2em;
            line-height: 1;
        }

        .header-left .title-group {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .header-left h1 {
            font-size: 1.6em;
            margin: 0;
            font-weight: 700;
            line-height: 1.2;
        }

        .header-left p {
            font-size: 0.85em;
            opacity: 0.85;
            margin: 0;
            line-height: 1.3;
        }

        .user-card {
            background: white;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 12px;
            width: 100%;
            margin: 0; /* 移除边距，由外层容器控制 */
        }

        .user-card .user-info {
            display: flex;
            flex-direction: column;
            gap: 6px;
            flex: 1;
        }

        .user-card .user-name {
            font-size: 0.9em;
            color: #666;
            margin: 0;
            font-weight: 500;
        }

        .user-card .user-balance {
            font-weight: 600;
            font-size: 0.95em;
            margin: 0;
            color: #28a745;
        }

        .user-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            flex-shrink: 0;
        }

        .chart-btn {
            background: #17a2b8;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.8em;
            font-weight: 500;
            transition: all 0.2s;
            white-space: nowrap;
            display: inline-block;
        }

        .chart-btn:hover {
            background: #138496;
            transform: translateY(-1px);
            color: white;
        }

        .reset-btn {
            background: #ffc107;
            color: #212529;
            border: none;
            padding: 8px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.8em;
            font-weight: 500;
            transition: all 0.2s;
            white-space: nowrap;
        }

        .reset-btn:hover {
            background: #e0a800;
            transform: translateY(-1px);
        }

        .logout-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.8em;
            transition: all 0.2s;
            white-space: nowrap;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header {
                padding: 12px 15px;
            }
            
            .header-content {
                flex-direction: column;
                gap: 12px;
                align-items: flex-start;
            }
            
            .header-left {
                gap: 10px;
            }
            
            .header-left .logo {
                font-size: 1.5em;
            }
            
            .header-left h1 {
                font-size: 1.3em;
            }
            
            .header-left p {
                font-size: 0.8em;
            }
            
            .user-card {
                width: 100%;
                min-width: unset;
            }
        }

        .main-content {
            padding: 0 30px 30px 30px;
        }

        .top-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .bottom-section {
            width: 100%;
        }
        
        .section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-top: 10px;
            border: 1px solid #e9ecef;
            height: fit-content;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .section-header h2 {
            margin: 0;
        }

        .server-status {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 600;
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #dc3545;
        }

        .status-indicator.connected {
            background: #28a745;
        }

        .status-indicator.connecting {
            background: #ffc107;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #4facfe;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #4facfe;
        }
        
        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
            width: 100%;
        }
        
        .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .status {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 600;
        }
        
        .status.connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 在section-header中的状态样式 */
        .section-header .status {
            padding: 6px 12px;
            margin-bottom: 0;
            font-size: 0.85em;
            border-radius: 20px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .section-header .status.connected {
            background: #d1f2eb;
            color: #0e6b47;
            border: 1px solid #a3d9d0;
        }
        
        .section-header .status.disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 交易面板左右布局 */
        .trading-layout {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            align-items: start;
        }

        .trading-left {
            /* background: #f8f9fa; */
            background: #f3f2f2;
            padding: 20px;
            border-radius: 10px;
            border: 1px solid #e9ecef;
        }

        .trading-right {
            /* background: #f8f9fa; */
            background: #f3f2f2;
            padding: 20px;
            border-radius: 10px;
            border: 1px solid #e9ecef;
        }

        .trading-left h2,
        .trading-right h2 {
            margin-top: 0;
            margin-bottom: 10px;
            color: #495057;
        }

        /* 响应式设计 - 移动端 */
        @media (max-width: 768px) {
            .trading-layout {
                grid-template-columns: 1fr;
                gap: 20px;
            }
        }
        
        .prices {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }

        /* 交易面板中的价格布局 */
        .trading-right .prices {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .trading-right .price-card {
            background: white;
            border: 1px solid #dee2e6;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .price-card {
            background: white;
            padding: 16px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            text-align: center;
        }
        
        .price-card h3 {
            color: #333;
            /* margin-bottom: 10px; */
        }
        
        .price-card .price {
            font-size: 1.8em;
            font-weight: bold;
            color: #4facfe;
        }
        
        .symbol-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 20px;
        }

        .symbol-btn {
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s;
            text-align: center;
        }

        .symbol-btn:hover {
            border-color: #4facfe;
            background: #f8f9fa;
        }

        .symbol-btn.active {
            border-color: #4facfe;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .period-category {
            margin-bottom: 15px;
        }

        .period-category-title {
            font-size: 14px;
            font-weight: 600;
            color: #495057;
            margin-bottom: 8px;
            padding-left: 2px;
            border-left: 3px solid #28a745;
            padding-left: 8px;
        }

        .period-buttons {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
        }

        /* 币安周期使用4列布局 */
        .period-category:last-child .period-buttons {
            grid-template-columns: repeat(4, 1fr);
        }

        .period-btn {
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            background: white;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
            text-align: center;
        }

        .period-btn:hover {
            border-color: #28a745;
            background: #f8f9fa;
        }

        .period-btn.active {
            border-color: #28a745;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .period-btn.test {
            border-color: #ffc107;
        }

        .period-btn.test:hover {
            border-color: #ffc107;
            background: #fff3cd;
        }

        .period-btn.test.active {
            border-color: #ffc107;
            background: linear-gradient(135deg, #ffc107 0%, #ffca2c 100%);
            color: #212529;
        }
        
        .contracts-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            font-size: 13px; /* 减小字体以适应更多列 */
            /* 移除最小宽度限制，让表格自适应容器 */
        }

        .contracts-table th,
        .contracts-table td {
            padding: 6px 8px; /* 适当增加内边距 */
            text-align: left;
            border-bottom: 1px solid #e9ecef;
            font-size: 11px; /* 统一字体 */
        }
        
        .time-cell {
            font-family: 'Courier New', monospace; /* 使用等宽字体 */
            font-size: 11px; /* 适当增加字体 */
            color: #666;
            white-space: nowrap; /* 防止时间换行 */
            width: 155px; /* 适当增加时间列宽度 */
            max-width: 125px;
        }
        
        /* 盈亏列样式调整 */
        .profit-cell {
            width: 75px; /* 适当增加盈亏列宽度 */
            max-width: 75px;
            white-space: nowrap;
            font-size: 11px;
        }
        
        /* 其他列宽度控制 - 适当增加 */
        .contracts-table th:nth-child(1), .contracts-table td:nth-child(1) { width: 55px; } /* 交易对 */
        .contracts-table th:nth-child(2), .contracts-table td:nth-child(2) { width: 65px; } /* 方向 */
        .contracts-table th:nth-child(3), .contracts-table td:nth-child(3) { width: 45px; } /* 周期 */
        .contracts-table th:nth-child(4), .contracts-table td:nth-child(4) { width: 65px; } /* 金额 */
        .contracts-table th:nth-child(5), .contracts-table td:nth-child(5) { width: 75px; } /* 锚定价格 */
        .contracts-table th:nth-child(6), .contracts-table td:nth-child(6) { width: 75px; } /* 结算价格 */
        .contracts-table th:nth-child(7), .contracts-table td:nth-child(7) { width: 65px; } /* 价差 */
        .contracts-table th:nth-child(8), .contracts-table td:nth-child(8) { width: 65px; } /* 状态 */
        .contracts-table th:nth-child(12), .contracts-table td:nth-child(12) { width: 80px; } /* 倒计时 */

        /* Toast消息样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
            pointer-events: none;
        }

        .toast {
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 10px;
            font-size: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s ease-in-out;
            pointer-events: auto;
            max-width: 300px;
            word-wrap: break-word;
        }

        .toast.show {
            transform: translateX(0);
            opacity: 1;
        }

        .toast.toast-info {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        .toast.toast-success {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }

        .toast.toast-warning {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }

        .toast.toast-error {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }

        .contracts-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }

        .contracts-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-active {
            background: #fff3cd;
            color: #856404;
        }

        .status-settled {
            background: #d4edda;
            color: #155724;
        }

        .status-loss {
            background: #f8d7da;
            color: #721c24;
        }

        .status-unknown {
            background: #f8d7da;
            color: #721c24;
        }

        .countdown {
            font-family: monospace;
            font-weight: bold;
            color: #dc3545;
        }

        .profit-positive {
            color: #28a745;
            font-weight: bold;
        }

        .profit-negative {
            color: #dc3545;
            font-weight: bold;
        }

        .price-diff-positive {
            color: #28a745;
            font-weight: bold;
        }

        .price-diff-negative {
            color: #dc3545;
            font-weight: bold;
        }

        .price-diff-neutral {
            color: #6c757d;
            font-weight: bold;
        }

        /* 用户统计信息样式 */
        .user-stats {
            margin-top: 15px;
            margin-bottom: 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .stats-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }

        .stats-row:last-child {
            margin-bottom: 0;
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex: 1;
            padding: 0 5px;
        }

        .stat-label {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 4px;
            font-weight: 500;
        }

        .stat-value {
            font-size: 14px;
            font-weight: 600;
            color: #495057;
        }

        .stat-value.positive {
            color: #28a745;
        }

        .stat-value.negative {
            color: #dc3545;
        }

        /* 消息提示组件样式 */
        .message-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            animation: fadeIn 0.3s ease-out;
        }

        .message-modal {
            background: white;
            border-radius: 15px;
            padding: 30px;
            min-width: 300px;
            max-width: 500px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            text-align: center;
            animation: slideIn 0.3s ease-out;
        }

        .message-icon {
            font-size: 3em;
            margin-bottom: 20px;
        }

        .message-title {
            font-size: 1.5em;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }

        .message-content {
            font-size: 1.1em;
            color: #666;
            margin-bottom: 25px;
            line-height: 1.5;
        }

        .message-btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
            min-width: 100px;
        }

        .message-btn:hover {
            transform: translateY(-2px);
        }

        .message-btn.success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .message-btn.error {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }

        .message-btn.warning {
            background: linear-gradient(135deg, #ffc107 0%, #ffca2c 100%);
            color: #212529;
        }

        .message-btn.info {
            background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
        }

        .message-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from { 
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to { 
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        .direction-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }
        
        .btn-up {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .btn-down {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .prices {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-content">
                <div class="header-left">
                    <div class="logo">🚀</div>
                    <div class="title-group">
                        <h1>事件合约交易平台</h1>
                    <p>基于加密货币价格预测的智能合约交易</p>
                </div>
                </div>

            </div>
        </div>
        
        <div class="main-content">
            <!-- 左侧：用户和交易 -->
            <div class="left-panel">
                <!-- 用户认证 -->
                <div class="section" id="authSection">
                    <!-- 登录表单 -->
                    <div id="loginForm">
                        <h2>🔐 用户登录</h2>
                        <div class="form-group">
                            <label for="loginUsername">用户名:</label>
                            <input type="text" id="loginUsername" placeholder="输入用户名">
                        </div>
                        <div class="form-group">
                            <label for="loginPassword">密码:</label>
                            <input type="password" id="loginPassword" placeholder="输入密码">
                        </div>
                        <button class="btn" onclick="loginUser()">登录</button>
                        <p style="text-align: center; margin-top: 15px;">
                            还没有账户？<a href="#" onclick="showRegisterForm()" style="color: #007bff; text-decoration: none;">注册新账户</a>
                        </p>
                </div>
                
                    <!-- 注册表单 -->
                    <div id="registerForm" style="display: none;">
                        <h2>📝 用户注册</h2>
                    <div class="form-group">
                            <label for="registerUsername">用户名:</label>
                            <input type="text" id="registerUsername" placeholder="输入用户名（至少2个字符）">
                    </div>
                        <div class="form-group">
                            <label for="registerPassword">密码:</label>
                            <input type="password" id="registerPassword" placeholder="输入密码（至少6个字符）">
                        </div>
                        <div class="form-group">
                            <label for="confirmPassword">确认密码:</label>
                            <input type="password" id="confirmPassword" placeholder="再次输入密码">
                        </div>
                        <button class="btn" onclick="registerUser()">注册账户</button>
                        <p style="text-align: center; margin-top: 15px;">
                            已有账户？<a href="#" onclick="showLoginForm()" style="color: #007bff; text-decoration: none;">返回登录</a>
                        </p>
                    </div>
                </div>
                
                <!-- 交易面板：创建合约和实时价格 -->
                <div class="section">
                    <div id="tradingSection" style="display: none;">
                        <div class="trading-layout">
                            <!-- 左侧：创建合约 -->
                            <div class="trading-left">
                                <h2>📈 创建合约</h2>
                        <div class="form-group">
                            <label>选择交易对:</label>
                                                         <div class="symbol-buttons">
                                 <div class="symbol-btn active" onclick="selectSymbol('BTCUSDT', this)">
                                     <div>🟠 BTC</div>
                                     <div id="btcPriceBtn">--</div>
                                 </div>
                                 <div class="symbol-btn" onclick="selectSymbol('ETHUSDT', this)">
                                     <div>🔷 ETH</div>
                                     <div id="ethPriceBtn">--</div>
                                 </div>
                             </div>
                        </div>

                        <div class="form-group">
                            <label>选择周期:</label>
                            
                            <!-- 测试周期 -->
                                                         <div class="period-category">
                                 <div class="period-category-title">🧪 测试周期</div>
                             <div class="period-buttons">
                                 <div class="period-btn test" onclick="selectPeriod('10s', this)">
                                     <div>⚡ 10秒</div>
                                 </div>
                                 <div class="period-btn test" onclick="selectPeriod('5m', this)">
                                     <div>🚀 5分钟</div>
                                 </div>
                                 </div>
                             </div>
                            
                            <!-- 币安周期 -->
                            <div class="period-category">
                                <div class="period-category-title">📊 币安周期</div>
                                                                <div class="period-buttons">
                                 <div class="period-btn active" onclick="selectPeriod('10m', this)">
                                     <div>⏰ 10分钟</div>
                                 </div>
                                 <div class="period-btn" onclick="selectPeriod('30m', this)">
                                     <div>⏱️ 30分钟</div>
                                 </div>
                                 <div class="period-btn" onclick="selectPeriod('1h', this)">
                                     <div>🕐 1小时</div>
                                 </div>
                                 <div class="period-btn" onclick="selectPeriod('1d', this)">
                                     <div>📅 1天</div>
                                     </div>
                                 </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="betAmount">下注金额 (USDT):</label>
                                                                         <input type="number" id="betAmount" placeholder="输入下注金额" min="1" step="0.01" value="5" max="250">
                        </div>

                        <div class="form-group">
                            <label>预测方向:</label>
                            <div class="direction-buttons">
                                <button class="btn btn-up" onclick="createContract('up')">📈 看涨</button>
                                <button class="btn btn-down" onclick="createContract('down')">📉 看跌</button>
                    </div>
                </div>
            </div>
            
                            <!-- 右侧：实时价格 -->
                            <div class="trading-right">
                                <div class="section-header">
                    <h2>💰 实时价格</h2>
                                    <div id="connectionStatus" class="status disconnected">
                                        🔴 未连接到服务器
                                    </div>
                                </div>
                    <div class="prices">
                        <div class="price-card">
                            <h3>ETH/USDT</h3>
                            <div id="ethPrice" class="price">--</div>
                        </div>
                        <div class="price-card">
                            <h3>BTC/USDT</h3>
                            <div id="btcPrice" class="price">--</div>
                                    </div>
                                </div>
                                
                                <!-- 用户信息区域 -->
                                <div id="userInfoSection" style="display: none; margin: 15px 0;">
                                    <div class="section-header">
                                        <h2>👤 用户信息</h2>
                                    </div>
                                    <div class="user-card" id="userCard">
                                        <div class="user-info">
                                            <div class="user-name">登录用户: <span id="headerUsername">--</span></div>
                                            <div class="user-balance">账户余额: <span id="headerBalance">0</span> USDT</div>
                                        </div>
                                        <div class="user-actions">
                                            <a href="klineChart.html" class="chart-btn" style="text-decoration: none;">📈 K线图表</a>
                                            <button class="reset-btn" onclick="resetAccount()">重置账户</button>
                                            <button class="logout-btn" onclick="logoutUser()">退出登录</button>
                                        </div>
                                    </div>
                                    
                                    <!-- 交易统计信息 -->
                                    <div class="user-stats">
                                        <div class="stats-row">
                                            <div class="stat-item">
                                                <span class="stat-label">做多胜率:</span>
                                                <span class="stat-value" id="longWinRate">--</span>
                                            </div>
                                            <div class="stat-item">
                                                <span class="stat-label">做空胜率:</span>
                                                <span class="stat-value" id="shortWinRate">--</span>
                                            </div>
                                        </div>
                                        <div class="stats-row">
                                            <div class="stat-item">
                                                <span class="stat-label">总胜率:</span>
                                                <span class="stat-value" id="totalWinRate">--</span>
                                            </div>
                                            <div class="stat-item">
                                                <span class="stat-label">胜利/总数:</span>
                                                <span class="stat-value" id="winCount">--</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </div>
                    </div>
                </div>
                
            <!-- 右侧：合约 -->
            <div class="right-panel">
                <!-- 合约列表 -->
                <div class="section" id="contractsSection" style="display: none;">
                    <h2>📋 我的合约</h2>
                    <div id="contractsContainer">
                        <table class="contracts-table" id="contractsTable" style="display: none;">
                            <thead>
                                <tr>
                                    <th>交易对</th>
                                    <th>方向</th>
                                    <th>周期</th>
                                    <th>金额</th>
                                    <th>锚定价格</th>
                                    <th>结算价格</th>
                                    <th>价差</th>
                                    <th>状态</th>
                                    <th>盈亏</th>
                                    <th>开仓时间</th>
                                    <th>平仓时间</th>
                                    <th>倒计时</th>
                                </tr>
                            </thead>
                            <tbody id="contractsTableBody">
                            </tbody>
                        </table>
                        <p id="noContractsMsg">暂无合约</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息提示组件 -->
    <div class="message-overlay" id="messageOverlay">
        <div class="message-modal">
            <div class="message-icon" id="messageIcon">📝</div>
            <div class="message-title" id="messageTitle">提示</div>
            <div class="message-content" id="messageContent">消息内容</div>
            <div class="message-buttons" id="messageButtons">
                <button class="message-btn" id="messageOkBtn" onclick="hideMessage()">确定</button>
            </div>
        </div>
    </div>

    <!-- Toast消息容器 -->
    <div class="toast-container" id="toastContainer"></div>

    <!-- 配置文件 -->
    <script src="config.js"></script>
    <script>
        let ws = null;
        let currentUser = null;
        let authToken = null;
        let prices = {};
        let contracts = [];
                 let selectedSymbol = 'BTCUSDT';
        let selectedPeriod = '10m';
        let countdownIntervals = {};

        // Toast消息函数（右上角非阻塞式）
        function showToast(content, type = 'info', duration = 3000) {
            const toastContainer = document.getElementById('toastContainer');
            
            // 创建Toast元素
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;
            toast.textContent = content;
            
            // 添加到容器
            toastContainer.appendChild(toast);
            
            // 显示动画
            setTimeout(() => {
                toast.classList.add('show');
            }, 100);
            
            // 自动隐藏
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 300);
            }, duration);
        }

        // 消息提示函数
        function showMessage(content, type = 'info', title = null, callback = null) {
            const overlay = document.getElementById('messageOverlay');
            const icon = document.getElementById('messageIcon');
            const titleEl = document.getElementById('messageTitle');
            const contentEl = document.getElementById('messageContent');
            const okBtn = document.getElementById('messageOkBtn');
            
            // 设置图标和样式
            const config = {
                success: { icon: '✅', title: '成功', className: 'success' },
                error: { icon: '❌', title: '错误', className: 'error' },
                warning: { icon: '⚠️', title: '警告', className: 'warning' },
                info: { icon: 'ℹ️', title: '提示', className: 'info' },
                confirm: { icon: '❓', title: '确认', className: 'warning' }
            };
            
            const typeConfig = config[type] || config.info;
            
            icon.textContent = typeConfig.icon;
            titleEl.textContent = title || typeConfig.title;
            contentEl.textContent = content;
            
            // 设置按钮样式
            okBtn.className = `message-btn ${typeConfig.className}`;
            
            // 设置回调
            okBtn.onclick = () => {
                hideMessage();
                if (callback) callback();
            };
            
            // 显示消息
            overlay.style.display = 'flex';
            
            // 点击背景关闭
            overlay.onclick = (e) => {
                if (e.target === overlay) {
                    hideMessage();
                }
            };
        }

        function showConfirm(content, title = '确认', confirmText = '确定', cancelText = '取消') {
            return new Promise((resolve) => {
                const overlay = document.getElementById('messageOverlay');
                const icon = document.getElementById('messageIcon');
                const titleEl = document.getElementById('messageTitle');
                const contentEl = document.getElementById('messageContent');
                const buttonsEl = document.getElementById('messageButtons');
                
                icon.textContent = '❓';
                titleEl.textContent = title;
                contentEl.textContent = content;
                
                // 创建确认和取消按钮
                buttonsEl.innerHTML = `
                    <button class="message-btn" id="confirmCancelBtn">${cancelText}</button>
                    <button class="message-btn warning" id="confirmOkBtn">${confirmText}</button>
                `;
                
                // 使用事件监听器绑定按钮
                const cancelBtn = document.getElementById('confirmCancelBtn');
                const okBtn = document.getElementById('confirmOkBtn');
                
                // 移除之前的监听器
                const newCancelBtn = cancelBtn.cloneNode(true);
                const newOkBtn = okBtn.cloneNode(true);
                cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn);
                okBtn.parentNode.replaceChild(newOkBtn, okBtn);
                
                // 添加新的监听器
                newCancelBtn.addEventListener('click', () => {
                    console.log('取消按钮被点击');
                    hideMessage();
                    resolve(false);
                });
                
                newOkBtn.addEventListener('click', () => {
                    console.log('确定按钮被点击');
                    hideMessage();
                    resolve(true);
                });
                
                overlay.style.display = 'flex';
                
                // 背景点击关闭
                overlay.onclick = (e) => {
                    if (e.target === overlay) {
                        console.log('背景被点击，执行取消');
                        hideMessage();
                        resolve(false);
                    }
                };
            });
        }



        function hideMessage() {
            const overlay = document.getElementById('messageOverlay');
            const buttonsEl = document.getElementById('messageButtons');
            
            overlay.style.display = 'none';
            
            // 重置按钮
            buttonsEl.innerHTML = '<button class="message-btn" id="messageOkBtn" onclick="hideMessage()">确定</button>';
            
            // 移除背景点击事件
            overlay.onclick = null;
        }

        // 连接WebSocket
        function connectWebSocket() {
            try {
                ws = new WebSocket(CONFIG.WEBSOCKET_URL);
                
                ws.onopen = function() {
                    updateConnectionStatus(true);
                    console.log('WebSocket连接成功');
                    
                    // 获取价格数据
                    sendMessage({action: 'get_prices'});
                };
                
                ws.onmessage = function(event) {
                    const data = JSON.parse(event.data);
                    handleMessage(data);
                };
                
                ws.onclose = function() {
                    updateConnectionStatus(false);
                    console.log('WebSocket连接关闭');
                    
                    // 5秒后重连
                    setTimeout(connectWebSocket, 5000);
                };
                
                ws.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                };
                
            } catch (error) {
                console.error('连接失败:', error);
                updateConnectionStatus(false);
                setTimeout(connectWebSocket, 5000);
            }
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusEl = document.getElementById('connectionStatus');
            if (connected) {
                statusEl.className = 'status connected';
                statusEl.textContent = '🟢 已连接到服务器';
            } else {
                statusEl.className = 'status disconnected';
                statusEl.textContent = '🔴 未连接到服务器';
            }
        }

        // 发送消息
        function sendMessage(message) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(message));
            } else {
                showMessage('未连接到服务器', 'error');
            }
        }

        // 处理收到的消息
        function handleMessage(data) {
            console.log('收到消息:', data);
            if (data.type === 'price_update') {
                updatePrice(data.data);
            } else if (data.user) {
                handleUserResponse(data);
            } else if (data.contract) {
                handleContractResponse(data);
            } else if (data.contracts) {
                updateContractsList(data.contracts);
            } else if (data.prices) {
                updatePrices(data.prices);
            } else if (data.error) {
                handleError(data.error);
            }
        }

        // 处理错误消息
        function handleError(errorMessage) {
            console.error('服务器错误:', errorMessage);
            
            // 如果是用户未找到错误，尝试重新创建用户
            if (errorMessage === 'User not found' && currentUser) {
                console.log('检测到用户不存在，尝试重新创建用户...');
                recreateUser();
                return;
            }
            
            // 其他错误直接显示
            showMessage(errorMessage, 'error');
        }

        // 重新创建用户


        // 重置用户会话
        function resetUserSession() {
            console.log('重置用户会话');
            currentUser = null;
            authToken = null;
            localStorage.removeItem('currentUser');
            localStorage.removeItem('authToken');
            
            // 隐藏用户卡片、交易区域和合约列表
            document.getElementById('userInfoSection').style.display = 'none';
            document.getElementById('authSection').style.display = 'block';
            document.getElementById('tradingSection').style.display = 'none';
            document.getElementById('contractsSection').style.display = 'none';
            
            // 显示登录表单
            showLoginForm();
            
            // 清空所有输入框
            document.getElementById('loginUsername').value = '';
            document.getElementById('loginPassword').value = '';
            document.getElementById('registerUsername').value = '';
            document.getElementById('registerPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            
            showToast('用户会话已重置，请重新登录', 'info');
        }

        // 重置账户
        async function resetAccount() {
            const confirmed = await showConfirm(
                '确认重置账户？',
                '此操作将清除您的所有历史订单数据并重置余额到初始状态，此操作不可逆！',
                '确认重置',
                '取消'
            );
            
            if (!confirmed) return;
            
            try {
                const response = await fetch(`${CONFIG.HTTP_API_URL}/api/auth/reset`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({
                        username: currentUser.username
                    })
                });
                
                const data = await response.json();
                
                if (response.ok && data.success) {
                    // 更新用户余额显示
                    currentUser.balance = data.new_balance;
                    document.getElementById('headerBalance').textContent = currentUser.balance.toFixed(2);
                    
                    // 重新加载合约列表（应该为空）
                    loadUserContracts();
                    
                    showToast('账户重置成功！', 'success');
                } else {
                    showMessage(data.error || '重置账户失败', 'error');
                }
            } catch (error) {
                console.error('重置账户错误:', error);
                showMessage('重置账户失败，请检查网络连接', 'error');
            }
        }

        // 退出登录
        async function logoutUser() {
            if (!currentUser) {
                return;
            }
            
            // 确认退出
            showConfirm(`确定要退出用户 "${currentUser.username}" 的登录吗？`, '退出登录', async () => {
                console.log(`用户 ${currentUser.username} 退出登录`);
                
                // 调用后端注销API
                if (authToken) {
                    try {
                        await fetch(`${CONFIG.HTTP_API_URL}/api/auth/logout`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ token: authToken })
                        });
                    } catch (error) {
                        console.error('注销API调用失败:', error);
                    }
                }
                
                // 清除用户数据
                currentUser = null;
                authToken = null;
                localStorage.removeItem('currentUser');
                localStorage.removeItem('authToken');
                
                // 清除所有倒计时定时器
                Object.values(countdownIntervals).forEach(interval => clearInterval(interval));
                countdownIntervals = {};
                
                // 重置界面
                document.getElementById('userInfoSection').style.display = 'none';
                document.getElementById('authSection').style.display = 'block';
                document.getElementById('tradingSection').style.display = 'none';
                document.getElementById('contractsSection').style.display = 'none';
                
                // 显示登录表单
                showLoginForm();
                
                // 清空表单和数据
                document.getElementById('loginUsername').value = '';
                document.getElementById('loginPassword').value = '';
                document.getElementById('registerUsername').value = '';
                document.getElementById('registerPassword').value = '';
                document.getElementById('confirmPassword').value = '';
                document.getElementById('betAmount').value = '';
                
                // 清空合约列表
                const tableEl = document.getElementById('contractsTable');
                const noMsgEl = document.getElementById('noContractsMsg');
                tableEl.style.display = 'none';
                noMsgEl.style.display = 'block';
                
                // 显示退出成功提示
                showToast('已成功退出登录！', 'success');
            });
        }

        // 更新价格显示
        function updatePrice(priceData) {
            console.log('更新价格:', priceData);
            prices[priceData.s] = priceData;

            const price = parseFloat(priceData.p);
            const displayPrice = price === 0 ? "连接失败" : price.toFixed(2);

            if (priceData.s === 'ETHUSDT') {
                const ethPriceEl = document.getElementById('ethPrice');
                const ethPriceBtnEl = document.getElementById('ethPriceBtn');
                if (ethPriceEl) {
                    ethPriceEl.textContent = displayPrice;
                    ethPriceEl.style.color = price === 0 ? '#dc3545' : '#4facfe';
                }
                if (ethPriceBtnEl) {
                    ethPriceBtnEl.textContent = displayPrice;
                    ethPriceBtnEl.style.color = price === 0 ? '#dc3545' : 'inherit';
                }
            } else if (priceData.s === 'BTCUSDT') {
                const btcPriceEl = document.getElementById('btcPrice');
                const btcPriceBtnEl = document.getElementById('btcPriceBtn');
                if (btcPriceEl) {
                    btcPriceEl.textContent = displayPrice;
                    btcPriceEl.style.color = price === 0 ? '#dc3545' : '#4facfe';
                }
                if (btcPriceBtnEl) {
                    btcPriceBtnEl.textContent = displayPrice;
                    btcPriceBtnEl.style.color = price === 0 ? '#dc3545' : 'inherit';
                }
            }
            
            // 更新活跃合约的价差显示
            updateActivePriceDifferences();
        }

        // 更新所有价格
        function updatePrices(pricesData) {
            console.log('更新所有价格:', pricesData);
            for (const symbol in pricesData) {
                updatePrice(pricesData[symbol]);
            }
        }

        // 更新活跃合约的价差显示
        function updateActivePriceDifferences() {
            // 只更新活跃合约的价差，避免重新渲染整个表格
            const tableBodyEl = document.getElementById('contractsTableBody');
            if (!tableBodyEl) return;
            
            const rows = tableBodyEl.querySelectorAll('tr');
            rows.forEach((row, index) => {
                // 检查这一行是否是活跃合约（通过状态列判断）
                const statusCell = row.querySelector('td:nth-child(8)'); // 状态列
                if (statusCell && statusCell.textContent.includes('进行中')) {
                    // 这是一个活跃合约，需要更新价差
                    // 注意：这里简化处理，实际中可能需要更复杂的逻辑来匹配合约数据
                    // 为了避免复杂性，我们在价格更新时重新加载合约列表
                    if (currentUser) {
                        // 降低频率，避免过度刷新
                        clearTimeout(window.priceDiffUpdateTimer);
                        window.priceDiffUpdateTimer = setTimeout(() => {
                            loadUserContracts();
                        }, 1000); // 1秒延迟防抖
                    }
                }
            });
        }

        // 选择交易对
        function selectSymbol(symbol, element) {
            selectedSymbol = symbol;

            // 更新按钮状态
            document.querySelectorAll('.symbol-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            element.classList.add('active');

            // 根据交易对设置最大下注金额
            const betAmountInput = document.getElementById('betAmount');
            if (symbol === 'ETHUSDT') {
                betAmountInput.max = 125;
            } else if (symbol === 'BTCUSDT') {
                betAmountInput.max = 250;
            }
            
            // 如果当前输入值超过最大值，则重置为最大值
            const currentValue = parseFloat(betAmountInput.value);
            const maxValue = parseFloat(betAmountInput.max);
            if (currentValue > maxValue) {
                betAmountInput.value = maxValue;
            }
        }

        // 监听下注金额输入，自动限制最大值
        function setupBetAmountListener() {
            const betAmountInput = document.getElementById('betAmount');
            
            // 监听输入事件
            betAmountInput.addEventListener('input', function() {
                const currentValue = parseFloat(this.value);
                const maxValue = parseFloat(this.max);
                
                // 如果输入值超过最大值，自动调整为最大值
                if (currentValue > maxValue) {
                    this.value = maxValue;
                    showToast(`已自动调整为最大金额: ${maxValue} USDT`, 'info');
                }
            });

            // 监听失去焦点事件（blur）
            betAmountInput.addEventListener('blur', function() {
                const currentValue = parseFloat(this.value);
                const maxValue = parseFloat(this.max);
                
                // 如果输入值超过最大值，自动调整为最大值
                if (currentValue > maxValue) {
                    this.value = maxValue;
                }
            });

            // 监听键盘输入事件（实时检查）
            betAmountInput.addEventListener('keyup', function() {
                const currentValue = parseFloat(this.value);
                const maxValue = parseFloat(this.max);
                
                // 如果输入值超过最大值，自动调整为最大值
                if (currentValue > maxValue) {
                    this.value = maxValue;
                }
            });
        }

        // 选择周期
        function selectPeriod(period, element) {
            selectedPeriod = period;

            // 更新按钮状态
            document.querySelectorAll('.period-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            element.classList.add('active');
        }

        // 保存用户信息到localStorage
        function saveUserInfo(user) {
            localStorage.setItem('currentUser', JSON.stringify(user));
        }

        // 从localStorage加载用户信息
        function loadUserInfo() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                try {
                    return JSON.parse(savedUser);
                } catch (e) {
                    console.error('Failed to parse saved user info:', e);
                    localStorage.removeItem('currentUser');
                }
            }
            return null;
        }

        // 更新用户界面
        function updateUserInterface(user) {
            currentUser = user;

            // 更新右上角用户卡片
            document.getElementById('headerUsername').textContent = user.username;
            document.getElementById('headerBalance').textContent = user.balance.toFixed(2);
            document.getElementById('userInfoSection').style.display = 'block';

            // 隐藏认证区域，显示交易区域和合约列表
            document.getElementById('authSection').style.display = 'none';
            document.getElementById('tradingSection').style.display = 'block';
            document.getElementById('contractsSection').style.display = 'block';

            // 保存用户信息
            saveUserInfo(user);
        }

        // 显示注册表单
        function showRegisterForm() {
            document.getElementById('loginForm').style.display = 'none';
            document.getElementById('registerForm').style.display = 'block';
        }
        
        // 显示登录表单
        function showLoginForm() {
            document.getElementById('registerForm').style.display = 'none';
            document.getElementById('loginForm').style.display = 'block';
        }
        
        // 用户登录
        async function loginUser() {
            const username = document.getElementById('loginUsername').value.trim();
            const password = document.getElementById('loginPassword').value.trim();
            
            if (!username || !password) {
                showMessage('请输入用户名和密码', 'warning');
                return;
            }
            
            try {
                const response = await fetch(`${CONFIG.HTTP_API_URL}/api/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentUser = data.user;
                    authToken = data.token;
                    
                    // 保存到localStorage
                    localStorage.setItem('authToken', authToken);
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    
                    // 更新界面
                    updateUserInterface(currentUser);
                    loadUserContracts();
                    
                    showToast(data.message || '登录成功', 'success');
                } else {
                    showMessage(data.error || '登录失败', 'error');
                }
            } catch (error) {
                console.error('登录错误:', error);
                showMessage('网络错误，请稍后重试', 'error');
            }
        }
        
        // 用户注册
        async function registerUser() {
            const username = document.getElementById('registerUsername').value.trim();
            const password = document.getElementById('registerPassword').value.trim();
            const confirmPassword = document.getElementById('confirmPassword').value.trim();
            
            if (!username || !password || !confirmPassword) {
                showMessage('请填写所有字段', 'warning');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage('两次输入的密码不一致', 'warning');
                return;
            }
            
            if (username.length < 2) {
                showMessage('用户名至少需要2个字符', 'warning');
                return;
            }
            
            if (password.length < 6) {
                showMessage('密码至少需要6个字符', 'warning');
                return;
            }
            
            try {
                const response = await fetch(`${CONFIG.HTTP_API_URL}/api/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentUser = data.user;
                    authToken = data.token;
                    
                    // 保存到localStorage
                    localStorage.setItem('authToken', authToken);
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    
                    // 更新界面
                    updateUserInterface(currentUser);
                    loadUserContracts();
                    
                    showToast(data.message || '注册成功', 'success');
                } else {
                    showMessage(data.error || '注册失败', 'error');
                }
            } catch (error) {
                console.error('注册错误:', error);
                showMessage('网络错误，请稍后重试', 'error');
            }
        }
        
        // 验证会话
        async function validateSession() {
            const token = localStorage.getItem('authToken');
            if (!token) {
                return false;
            }
            
            try {
                const response = await fetch(`${CONFIG.HTTP_API_URL}/api/auth/validate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ token: token })
                });
                
                const data = await response.json();
                
                if (data.success && data.valid && data.user) {
                    currentUser = data.user;
                    authToken = token;
                    return true;
                } else {
                    // 清除无效的token
                    localStorage.removeItem('authToken');
                    localStorage.removeItem('currentUser');
                    return false;
                }
            } catch (error) {
                console.error('会话验证错误:', error);
                return false;
            }
        }
        
        // 创建用户（保留旧接口兼容）
        function createUser() {
            const username = document.getElementById('username').value.trim();
            if (!username) {
                showMessage('请输入用户名', 'warning');
                return;
            }
            
            sendMessage({
                action: 'create_user',
                username: username
            });
        }

        // 处理用户响应
        function handleUserResponse(data) {
            if (data.success && data.user) {
                updateUserInterface(data.user);

                // 获取用户合约
                loadUserContracts();
            }
        }

        // 创建合约
        function createContract(direction) {
            if (!currentUser) {
                showMessage('请先创建用户账户', 'warning');
                return;
            }

            const betAmount = parseFloat(document.getElementById('betAmount').value);

            if (!betAmount || betAmount <= 0) {
                showMessage('请输入有效的下注金额', 'warning');
                return;
            }

            if (betAmount > currentUser.balance) {
                showMessage('余额不足', 'error');
                return;
            }

            // 检查最大下注限制
            const maxAmount = selectedSymbol === 'ETHUSDT' ? 125 : 250;
            if (betAmount > maxAmount) {
                showMessage(`${selectedSymbol === 'ETHUSDT' ? 'ETH' : 'BTC'}最大下注金额为${maxAmount} USDT`, 'warning');
                return;
            }

            sendMessage({
                action: 'create_contract',
                user_id: currentUser.username,
                symbol: selectedSymbol,
                period: selectedPeriod,
                direction: direction,
                bet_amount: betAmount
            });
        }

        // 处理合约响应
        function handleContractResponse(data) {
            if (data.success && data.contract) {
                // 调试：检查合约时间设置
                console.log('🔍 合约创建调试信息：');
                console.log('选择的周期:', selectedPeriod);
                console.log('合约周期:', data.contract.period);
                console.log('锚定时间戳:', data.contract.anchor_timestamp, '(', new Date(data.contract.anchor_timestamp).toLocaleTimeString(), ')');
                console.log('到期时间戳:', data.contract.expiry_timestamp, '(', new Date(data.contract.expiry_timestamp).toLocaleTimeString(), ')');
                const duration = data.contract.expiry_timestamp - data.contract.anchor_timestamp;
                console.log('实际时长:', duration / 1000, '秒');
                console.log('当前时间:', Date.now(), '(', new Date().toLocaleTimeString(), ')');
                const remaining = data.contract.expiry_timestamp - Date.now();
                console.log('剩余时间:', remaining / 1000, '秒');
                console.log('时间差（锚定-当前）:', (data.contract.anchor_timestamp - Date.now()) / 1000, '秒');
                
                showToast('合约创建成功！', 'success');

                // 更新用户余额
                currentUser.balance -= data.contract.bet_amount;
                document.getElementById('headerBalance').textContent = currentUser.balance.toFixed(2);

                // 保存更新后的用户信息
                saveUserInfo(currentUser);

                // 重置表单为默认值
                document.getElementById('betAmount').value = '5';

                // 重新加载合约列表（使用HTTP API）
                setTimeout(() => {
                loadUserContracts();
                }, 500); // 稍微延迟以确保后端已保存
            }
        }

        // 使用HTTP API加载用户合约
        async function loadUserContracts() {
            if (!currentUser) {
                console.log('没有当前用户，跳过加载合约');
                return;
            }
            
            try {
                console.log(`加载用户 ${currentUser.username} 的历史合约...`);
                const url = `${CONFIG.HTTP_API_URL}${CONFIG.API_ENDPOINTS.CONTRACTS}?user_id=${currentUser.username}`;
                const response = await fetch(url);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                console.log('HTTP API响应:', data);
                
                if (data.success && data.contracts) {
                    updateContractsList(data.contracts);
                    console.log(`✅ 成功加载 ${data.contracts.length} 个历史合约`);
                } else if (data.error) {
                    console.error('获取合约失败:', data.error);
                } else {
                    console.warn('未知的API响应格式:', data);
                }
            } catch (error) {
                console.error('加载用户合约失败:', error);
                // 降级到WebSocket方式
                console.log('降级使用WebSocket获取合约...');
                sendMessage({
                    action: 'get_contracts',
                    user_id: currentUser.username
                });
            }
        }

        // 格式化时间戳为精确到毫秒的时间字符串
        function formatTimestamp(timestamp, includeMilliseconds = true) {
            if (!timestamp) return '--';
            
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            const milliseconds_part = String(date.getMilliseconds()).padStart(3, '0');
            
            const dateStr = `${year}-${month}-${day}`;
            const timeStr = `${hours}:${minutes}:${seconds}`;
            
            if (includeMilliseconds) {
                return `${dateStr} ${timeStr}.${milliseconds_part}`;
            } else {
                return `${dateStr} ${timeStr}`;
            }
        }
        
        // 格式化ISO时间字符串为时间字符串
        function formatISOTimestamp(isoString, includeMilliseconds = false) {
            if (!isoString) return '--';
            
            const date = new Date(isoString);
            return formatTimestamp(date.getTime(), includeMilliseconds);
        }

        // 格式化倒计时
        function formatCountdown(milliseconds) {
            if (milliseconds <= 0) return '已到期';

            const seconds = Math.floor(milliseconds / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);

            if (days > 0) {
                return `${days}天 ${hours % 24}时 ${minutes % 60}分`;
            } else if (hours > 0) {
                return `${hours}时 ${minutes % 60}分 ${seconds % 60}秒`;
            } else if (minutes > 0) {
                return `${minutes}分 ${seconds % 60}秒`;
            } else {
                return `${seconds}秒`;
            }
        }

        // 更新合约列表
        function updateContractsList(contractsData) {
            const tableEl = document.getElementById('contractsTable');
            const tableBodyEl = document.getElementById('contractsTableBody');
            const noMsgEl = document.getElementById('noContractsMsg');

            // 清除现有的倒计时定时器
            Object.values(countdownIntervals).forEach(interval => clearInterval(interval));
            countdownIntervals = {};

            if (contractsData.length === 0) {
                tableEl.style.display = 'none';
                noMsgEl.style.display = 'block';
                return;
            }

            tableEl.style.display = 'table';
            noMsgEl.style.display = 'none';

            tableBodyEl.innerHTML = contractsData.map(contract => {
                const createdAt = new Date(contract.created_at).toLocaleString();

                let statusBadge = '';
                let profitCell = '';
                let countdownCell = '';

                if (contract.status === 'active') {
                    statusBadge = '<span class="status-badge status-active">进行中</span>';
                    profitCell = '--';
                    countdownCell = `<span class="countdown" id="countdown-${contract.id}">计算中...</span>`;
                } else if (contract.status === 'settled') {
                    const isProfit = contract.profit > 0;
                    statusBadge = `<span class="status-badge ${isProfit ? 'status-settled' : 'status-loss'}">${isProfit ? '盈利' : '亏损'}</span>`;
                    profitCell = `<span class="${isProfit ? 'profit-positive' : 'profit-negative'}">${isProfit ? '+' : ''}${contract.profit.toFixed(2)} USDT</span>`;
                    countdownCell = '已结算';
                } else {
                    statusBadge = '<span class="status-badge status-unknown">未知</span>';
                    profitCell = '退款';
                    countdownCell = '异常';
                }

                const symbolDisplay = contract.symbol === 'ETHUSDT' ? '🔷 ETH' : '🟠 BTC';
                const directionDisplay = contract.direction === 'up' ? '📈 看涨' : '📉 看跌';
                
                // 计算价差
                let priceDiffCell = '';
                let currentPrice = 0;
                
                if (contract.status === 'settled' && contract.final_price) {
                    // 已结算的合约：使用最终结算价格
                    currentPrice = contract.final_price;
                } else if (contract.status === 'active') {
                    // 进行中的合约：使用当前实时价格
                    const currentPriceData = prices[contract.symbol];
                    if (currentPriceData && currentPriceData.p) {
                        currentPrice = parseFloat(currentPriceData.p);
                    }
                }
                
                if (currentPrice > 0) {
                    const priceDiff = currentPrice - contract.anchor_price;
                    let adjustedDiff = priceDiff;
                    
                    // 根据买涨买跌调整价差符号
                    if (contract.direction === 'down') {
                        adjustedDiff = -priceDiff; // 买跌时价差取反
                    }
                    
                    let diffClass = '';
                    let diffSymbol = '';
                    if (adjustedDiff > 0) {
                        diffClass = 'price-diff-positive';
                        diffSymbol = '+';
                    } else if (adjustedDiff < 0) {
                        diffClass = 'price-diff-negative';
                        diffSymbol = '';
                    } else {
                        diffClass = 'price-diff-neutral';
                        diffSymbol = '';
                    }
                    
                    priceDiffCell = `<span class="${diffClass}">${diffSymbol}${adjustedDiff.toFixed(2)}</span>`;
                } else {
                    priceDiffCell = '--';
                }
                
                const finalPriceDisplay = contract.final_price ? contract.final_price.toFixed(2) : (currentPrice > 0 ? currentPrice.toFixed(2) : '--');
                
                // 格式化开仓时间和平仓时间（不显示毫秒）
                const openTimeDisplay = formatISOTimestamp(contract.created_at, false);
                const closeTimeDisplay = contract.settled_at ? formatISOTimestamp(contract.settled_at, false) : '--';

                return `
                    <tr>
                        <td>${symbolDisplay}</td>
                        <td>${directionDisplay}</td>
                        <td>${contract.period}</td>
                        <td>${contract.bet_amount} USDT</td>
                        <td>${contract.anchor_price.toFixed(2)}</td>
                        <td>${finalPriceDisplay}</td>
                        <td>${priceDiffCell}</td>
                        <td>${statusBadge}</td>
                        <td class="profit-cell">${profitCell}</td>
                        <td class="time-cell">${openTimeDisplay}</td>
                        <td class="time-cell">${closeTimeDisplay}</td>
                        <td>${countdownCell}</td>
                    </tr>
                `;
            }).join('');

            // 为活跃合约设置倒计时
            contractsData.forEach(contract => {
                if (contract.status === 'active') {
                    startCountdown(contract.id, contract.expiry_timestamp);
                }
            });

            // 更新交易统计信息
            updateTradingStats(contractsData);
        }

        // 更新交易统计信息
        function updateTradingStats(contractsData) {
            // 只统计已结算的合约
            const settledContracts = contractsData.filter(contract => contract.status === 'settled');
            
            if (settledContracts.length === 0) {
                // 没有已结算的合约
                document.getElementById('longWinRate').textContent = '--';
                document.getElementById('shortWinRate').textContent = '--';
                document.getElementById('totalWinRate').textContent = '--';
                document.getElementById('winCount').textContent = '0/0';
                return;
            }
            
            // 分类统计
            const longContracts = settledContracts.filter(contract => contract.direction === 'up');
            const shortContracts = settledContracts.filter(contract => contract.direction === 'down');
            
            // 胜利条件：profit > 0
            const longWins = longContracts.filter(contract => contract.profit > 0).length;
            const shortWins = shortContracts.filter(contract => contract.profit > 0).length;
            const totalWins = longWins + shortWins;
            
            // 计算胜率
            const longWinRate = longContracts.length > 0 ? (longWins / longContracts.length * 100) : 0;
            const shortWinRate = shortContracts.length > 0 ? (shortWins / shortContracts.length * 100) : 0;
            const totalWinRate = settledContracts.length > 0 ? (totalWins / settledContracts.length * 100) : 0;
            
            // 更新显示
            updateStatDisplay('longWinRate', longWinRate, longContracts.length > 0);
            updateStatDisplay('shortWinRate', shortWinRate, shortContracts.length > 0);
            updateStatDisplay('totalWinRate', totalWinRate, true);
            document.getElementById('winCount').textContent = `${totalWins}/${settledContracts.length}`;
        }
        
        // 更新统计显示
        function updateStatDisplay(elementId, rate, hasData) {
            const element = document.getElementById(elementId);
            if (!hasData) {
                element.textContent = '--';
                element.className = 'stat-value';
                return;
            }
            
            element.textContent = `${rate.toFixed(1)}%`;
            
            // 根据胜率设置颜色
            element.className = 'stat-value';
            if (rate >= 60) {
                element.classList.add('positive');
            } else if (rate < 40) {
                element.classList.add('negative');
            }
        }

        // 开始倒计时
        function startCountdown(contractId, expiryTimestamp) {
            const countdownEl = document.getElementById(`countdown-${contractId}`);
            if (!countdownEl) return;

            const updateCountdown = () => {
                const now = Date.now();
                const remaining = expiryTimestamp - now;
                countdownEl.textContent = formatCountdown(remaining);

                if (remaining <= 0) {
                    clearInterval(countdownIntervals[contractId]);
                    delete countdownIntervals[contractId];
                    countdownEl.textContent = '已到期';
                    // 合约到期，刷新合约列表以获取最新状态
                    console.log(`合约 ${contractId} 已到期，刷新合约列表...`);
                    setTimeout(() => loadUserContracts(), 2000); // 稍微延迟等待后端结算
                }
            };

            updateCountdown(); // 立即更新一次
            countdownIntervals[contractId] = setInterval(updateCountdown, 1000);
        }

                // 处理用户响应（保留旧WebSocket兼容性）
        function handleUserResponse(data) {
            if (data.success && data.user) {
                updateUserInterface(data.user);
                loadUserContracts();
            }
            }

        // 页面加载完成后连接WebSocket
        window.addEventListener('load', async function() {
            connectWebSocket();

            // 设置下注金额输入监听器
            setupBetAmountListener();

            // 验证保存的会话
            const isValidSession = await validateSession();
            if (isValidSession && currentUser) {
                updateUserInterface(currentUser);
                loadUserContracts();
            } else {
                // 没有有效会话，显示登录表单
                resetUserSession();
            }

            // 定期刷新合约列表
            setInterval(() => {
                if (currentUser) {
                    loadUserContracts();
                }
            }, CONFIG.CONTRACT_REFRESH_INTERVAL); // 使用配置中的刷新间隔
        });
    </script>
</body>
</html>
